import React, { useState, useEffect } from 'react'
import Search from '@/components/search/Search'
import { useSelector } from 'react-redux'
import { useActions } from '@/hooks/useActions'
import * as actions from './actionCreator'

import {
  CategoryWrapper,
  SliderWrapper
} from './StyledCategory'

import classNames from 'classnames'

import axios from 'axios'

import CategoryComponent from '@/components/category/Category'


function Category() {
  const [switcherTab, setSwitcherTab] = useState('category')
  const [categoryData, setCategoryData] = useState(null)
  const actionsObj = useActions(actions)

  const slideClass = curTab => {
    return {
      tabActive: classNames({
        active: switcherTab === curTab,
      }), 
      slideRight: classNames({
        right: switcherTab === 'material'
      })
    }
  }

  const changeTab = tab => {
    return () => {
      // dispatch({type: CHANGE, tab})
      actionsObj.change(tab === 'category' ? '热门' : '肉类')
      setSwitcherTab(tab)
    }
  }

  useEffect(
    function() {
      // async await 函数在useEffect里使用，需要在第一个函数体里返回一个
      // 立即调用的函数表达式，在这个函数里加async
      (async () => {
        let result = await axios({
          url: '/api/category'
        })
    
        setCategoryData(result.data.data)
      })()
    },
    []
  )

  return (
    <CategoryWrapper>
      <header>
        <SliderWrapper
          borderWidth="1px"
          borderColor="#fff"
          borderRadius={0.15}
        >
          <li 
            className={slideClass('category').tabActive}
            onClick={changeTab('category')}
          >分类</li>
          <li 
            className={slideClass('material').tabActive}
            onClick={changeTab('material')}
          >食材</li>
          <li className={slideClass().slideRight}></li>
        </SliderWrapper>
      </header>
      <Search
        outerBg="#fff"
        innerBg="#f6f6f9"
      />
      {
        categoryData && (
          <CategoryComponent
            categoryData = {categoryData[switcherTab]}
          ></CategoryComponent>
        )
      }
    </CategoryWrapper>
  );
}

export default Category